# This playbook retrieves data that Fedora knows about a username and/or e-mail address.
#
# Please read http://fedora-infra-docs.readthedocs.io/en/latest/sysadmin-guide/sops/gdpr_sar.html
# for information about how to use this playbook and how to integration applications with it.
- name: Gather SAR data
  hosts: sar
  tasks:
    - command: "{{ sar_script }}"
      environment:
        SAR_USERNAME: "{{ sar_fas_user }}"
        SAR_EMAIL: "{{ sar_email }}"
      register: sar_data
      become: yes
      become_user: "{{ sar_script_user }}"
    # Let's make this a more conveniently expressed variable.
    - set_fact:
        sar_data: "{{ sar_data['stdout'] }}"

- name: Create the archive
  hosts: localhost
  tasks:
    - name: "Create the archive"
      block:
        # Create a safe place to store the files.
        - command: "mktemp -d"
          register: sar_tmp_dir
        # Let's make this a more conveniently expressed variable.
        - set_fact:
            sar_tmp_dir: "{{ sar_tmp_dir['stdout'] }}"
        # Write files from each service into our protected folder.
        - copy:
            content: "{{ hostvars[item]['sar_data'] }}"
            dest: "{{ sar_tmp_dir }}/{{ hostvars[item]['sar_output_file'] }}"
          loop: "{{ groups['sar'] }}"
        # Generate a private tarball of the files from each service.
        - shell: "umask 0077 && tar --transform \"s:^:{{ sar_fas_user }}_{{ sar_email }}/:\" -czf {{ sar_tmp_dir }}/{{ sar_fas_user }}_{{ sar_email }}.tar.gz *"
          args:
            chdir: "{{ sar_tmp_dir }}"
        # Move the tarball into the desired pick up location.
        - command: "mv {{ sar_tmp_dir }}/{{ sar_fas_user }}_{{ sar_email }}.tar.gz {{ sar_tar_output_path }}"
      always:
        # Let's clean up our temporary directory.
        - command: "rm -r {{ sar_tmp_dir }}"
